package service;

import java.io.IOException;

import kr.pe.okjsp.rss.RSSProxy;

public class NaverShopping {
	
	/**
	 * @param query
	 * @return
	 * @throws IOException
	 */
	public static String getProduct(String query) throws IOException {
		String path = "http://openapi.naver.com/search?key=e74f4e476ae4695a5098fe088812a820&query="+query
		+"&display=5&start=1&target=shop&sort=sim";
		String xml = RSSProxy.getXML(path,"utf-8");
		String product = getValue(xml, "item");

		String title = getValue(product, "title");
		title = title.replaceAll("&lt;", "<");
		title = title.replaceAll("&gt;", ">");
		
		String link = getValue(product, "link");
		
		String image = getValue(product, "image");
		
		String lprice = getValue(product, "lprice");
		
		String htmlCode = "<link rel=\"stylesheet\" type=\"text/css\" href=\"http://www.okjsp.pe.kr/mashup/style.css\" />"+
				"<table class=\"shopg\"><tr><td rowspan=\"2\"><a href=\""+link+"\">" +
				"<img src=\""+image+"\"></a></td>" +
				"<td><div class=\"shopg_name\">"+title+"</div></td></tr>" +
				"<tr><td>"+lprice+"</td></tr></table>";
		return htmlCode;
	}

	private static String getValue(String product, String nodeName) {
		int tagStart = product.indexOf("<"+nodeName+">");
		int tagEnd = product.indexOf("</"+nodeName+">");
		return product.substring(tagStart+nodeName.length()+2, tagEnd);
	}

}
